package com.shundr.shipper.cargo.adapter;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shundr.shipper.R;
import com.shundr.shipper.cargo.model.CargoInfo;
import com.shundr.shipper.common.http.CommonRequest;
import com.shundr.shipper.common.util.CommonConfig;
import com.shundr.shipper.common.util.DateUtil;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.truck.ContactTrucker;
import com.shundr.shipper.truck.ContactTrucker.OnCallListener;
import com.shundr.shipper.user.LoginActivity;

/**
 * 
 * CargoAdapter 货源列表适配器
 * 
 * @author larry 2015-4-13 下午4:26:47 
 * @version 1.0.0
 *
 */
public class CargoAdapter extends BaseAdapter{
	private List<CargoInfo> mList;
	private Context mContext;
	/**
	 * 收藏position
	 */
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CommonRequest.ADD_FAVORITE_SUCCEED:
				try {
					ToastHelper.toastShort(mContext,msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				try {
					ToastHelper.toastShort(mContext,msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int index) {
		return mList.get(index);
	}

	@Override
	public long getItemId(int id) {
		return id;
	}

	public CargoAdapter(List<CargoInfo> mlist, Context mContext) {
		super();
		this.mList = mlist;
		this.mContext = mContext;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup viewGroup) {
		ViewHold viewHold = null;
		if(convertView == null){
			convertView = LayoutInflater.from(mContext).inflate(R.layout.item_cargo_list,null);
			viewHold = new ViewHold();
			viewHold.tvFrom = (TextView) convertView.findViewById(R.id.tv_from);
			viewHold.tvTo = (TextView) convertView.findViewById(R.id.tv_to);
			viewHold.tvLength = (TextView) convertView.findViewById(R.id.tv_length);
			viewHold.tvWeight = (TextView) convertView.findViewById(R.id.tv_weight);
			viewHold.tvTypeCargo = (TextView) convertView.findViewById(R.id.tv_type_cargo);
			viewHold.tvTypeCar = (TextView) convertView.findViewById(R.id.tv_type_car);
			viewHold.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
			viewHold.layoutCollection = (LinearLayout) convertView.findViewById(R.id.layout_collect);
			viewHold.layoutCall = (LinearLayout) convertView.findViewById(R.id.layout_call);
			viewHold.tvDescription = (TextView) convertView.findViewById(R.id.tv_description);
			viewHold.ivFavoriteStatus=(ImageView)convertView.findViewById(R.id.iv_favorite_status);
			viewHold.tvCollect=(TextView)convertView.findViewById(R.id.tv_collect_status);
			convertView.setTag(viewHold);
		}else{
			viewHold = (ViewHold) convertView.getTag();
		}
		try {
			final CargoInfo info = mList.get(position);
			viewHold.tvFrom.setText(info.getCargoSrcPlace());
			viewHold.tvTo.setText(info.getCargoDstPlace());
			if (StringUtil.isNull(info.getCargoTruckLength())) {
				viewHold.tvLength.setText("不限");
			} else {
				if(StringUtil.isEqual(info.getCargoTruckLength(), "23")){
					viewHold.tvLength.setText(info.getCargoTruckLength() + "米以上");
				}else{
					viewHold.tvLength.setText(info.getCargoTruckLength() + "米");
				}
			}
			if (StringUtil.isNull(info.getCargoAmount())) {
				viewHold.tvWeight.setText("若干");
			} else {
				viewHold.tvWeight.setText(info.getCargoAmount() + info.getCargoUnitName());
			}
			viewHold.tvTypeCargo.setText(info.getCargoCategory());
			String cart = info.getCargoTruckType();

			if (cart == null) {
				viewHold.tvTypeCar.setText("");
			} else {
				viewHold.tvTypeCar.setText(cart);
			}
//			String description = info.getCargoDescription().trim().replace(",", "");
//			viewHold.tvDescription.setText(description);

			viewHold.tvTime.setText(DateUtil.getInterval(info.getCargoResendTime()));
			viewHold.layoutCollection.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(LContext.isLogin()){
						if(info.isFavorited()){
							ToastHelper.toastShort(mContext, "您已经收藏了此货源");
							return;
						}
						//收藏货源
						new CommonRequest(mContext, mHandler).addFavorite(info.getCargoId(), CommonConfig.OPERATE_OBJECT_CARGO);
		        	}else{
		        		mContext.startActivity(new Intent(mContext, LoginActivity.class));
		        	}
				}
			});
			viewHold.layoutCall.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(LContext.isLogin()){
						new CommonRequest(mContext, new Handler()).saveOperateHistory(info.getCargoId(), CommonConfig.OPERATE_OBJECT_CARGO, CommonConfig.OPERATE_CALL,"");
						if (LContext.getUserValidationStatus() != -1) {//认证完
							OnCallPhone(info);
						}else{//未认证通过
							ContactTrucker trucker = new ContactTrucker(mContext);
							trucker.setCallListener(new OnCallListener() {
								
								@Override
								public void onCall() {
									OnCallPhone(info);
								}
							});
						}
		        	}else{
		        		mContext.startActivity(new Intent(mContext, LoginActivity.class));
		        	}
				}
			});
			if(info.getLocalType() != null){
				if(info.getLocalType() == CargoInfo.CargoLocalType.unread){
					convertView.setBackgroundResource(R.drawable.item_common_selector);
				}else{
					convertView.setBackgroundResource(R.drawable.item_common_gray_selector);
				}
			}
			if(info.isFavorited()){
				viewHold.tvCollect.setText("已收藏");
				viewHold.ivFavoriteStatus.setBackgroundResource(R.drawable.iv_favorite_yes);
			}else{
				viewHold.tvCollect.setText("收藏货源");
				viewHold.ivFavoriteStatus.setBackgroundResource(R.drawable.iv_favorite_no);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	private void OnCallPhone(CargoInfo info){
		if(!StringUtil.isNull(info.getCargoCompanyPhone1())){
			String mobileText = info.getCargoCompanyPhone1().replace("-", "");
			Intent intent = new Intent();// 创建一个意图对象，用来激发拨号的Activity
			intent.setAction("android.intent.action.CALL");
			intent.setData(Uri.parse("tel:" + mobileText));
			mContext.startActivity(intent);// 方法内部会自动添加类别,android.intent.category.DEFAULT
		}else{
			ToastHelper.toastShort(mContext, "该货主未提供联系电话");
		}
	}

	static class ViewHold{
		TextView tvFrom;
		TextView tvTo;
		TextView tvLength;
		TextView tvWeight;
		TextView tvTypeCargo;
		TextView tvTypeCar;
		TextView tvTime;
		TextView tvDescription;
		TextView tvCollect;
		
		ImageView ivFavoriteStatus;
		
		LinearLayout layoutCollection;
		LinearLayout layoutCall;
	}

}
